using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.Approval;

namespace RBAC.Write.Api.Controllers
{
    /// <summary>
    /// 审批流程写入API控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApprovalController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ApprovalController> logger;

        public ApprovalController(IMediator mediator, ILogger<ApprovalController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 新增审批流程（可同时创建节点）
        /// </summary>
        /// <param name="request">创建审批流程命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果，Data为新建流程ID</returns>
        [HttpPost]
        public async Task<APIResult<long>> CreateApprovalProcess(CreateApprovalProcessCommand request, CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始创建审批流程，流程名称: {ProcessName}", request.ProcessName);
                var result = await mediator.Send(request, cancellationToken);
                logger.LogInformation("创建审批流程完成，流程名称: {ProcessName}, 结果: {Code}", request.ProcessName, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "创建审批流程时发生异常，流程名称: {ProcessName}", request.ProcessName);
                return new APIResult<long>
                {
                    Code = APIEnums.Error,
                    Msg = $"创建审批流程失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 更新审批流程
        /// </summary>
        /// <param name="request">更新审批流程命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        [HttpPut]
        public async Task<APIResult<int>> UpdateApprovalProcess(UpdateApprovalProcessCommand request, CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始更新审批流程，ID: {Id}, 流程名称: {ProcessName}", request.Id, request.ProcessName);
                var result = await mediator.Send(request, cancellationToken);
                logger.LogInformation("审批流程更新完成，ID: {Id}, 结果: {Code}", request.Id, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新审批流程时发生异常，ID: {Id}", request.Id);
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"更新审批流程失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除审批流程
        /// </summary>
        /// <param name="request">删除审批流程命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        [HttpDelete]
        public async Task<APIResult<int>> DeleteApprovalProcess(DeleteApprovalProcessCommand request, CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始删除审批流程，ID: {Id}", request.Id);
                var result = await mediator.Send(request, cancellationToken);
                logger.LogInformation("审批流程删除完成，ID: {Id}, 结果: {Code}", request.Id, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除审批流程时发生异常，ID: {Id}", request.Id);
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"删除审批流程失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpGet]
        public IActionResult TestConnection()
        {
            logger.LogInformation("审批流程写入API连接测试");
            return Ok(new { message = "审批流程写入API连接正常", timestamp = DateTime.Now });
        }
    }
}
